package sincro.common;
import java.io.InputStream;
import java.util.Properties;


import com.jcraft.jsch.ChannelExec;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.Session;
import common.Display;

public class SessionUtil {

	public static Session createSession(final String host, final String user, final String pass, final int port) {

		JSch jsch = new JSch();

		try {
			Display.log("Conectando con " + user + " en " + host + ":" + port);

			Session session = jsch.getSession(user, host, port);
			session.setPassword(pass);

			Properties prop = new Properties();
			prop.put("StrictHostKeyChecking", "no");
			prop.put("PreferredAuthentications", "keyboard-interactive,gssapi-with-mic,publickey,password");
			session.setConfig(prop);
			
			session.connect();

			Display.log("Conexion realizada");

			return session;

		} catch (Exception e) {
			Display.log("Se ha producido un error inesperado: " + e.getMessage());
			e.printStackTrace();
		}

		return null;
	}

	public static void closeSession(Session session) {
		session.disconnect();
		Display.log("Desconectado del servidor");
	}

	public static void execRemoteCommand(Session session, String command) {
		Display.log("Ejecutando el comando: " + command);
		try {
			ChannelExec chan = (ChannelExec) session.openChannel("exec");
			chan.setCommand(command);
			chan.setInputStream(null);
			chan.setErrStream(System.err);
			
			InputStream in = chan.getInputStream();
			chan.connect();

			byte[] tmp = new byte[1024];
			while (true) {
				while (in.available() > 0) {
					int i = in.read(tmp, 0, 1024);
					if (i < 0)
						break;
					Display.rawLog(new String(tmp, 0, i));
				}
				if (chan.isClosed()) {
					Display.log("exit-status: " + chan.getExitStatus());
					break;
				}
				try {
					Thread.sleep(1000);
				} catch (Exception ee) {
				}
			}
			chan.disconnect();
		} catch (Exception e) {
			Display.log("Se ha producido un error inesperado: " + e.getMessage());
			e.printStackTrace();
		}
	}
	
	public static void execRemoteCommandShowErr(Session session, String command) {
		Display.log("Ejecutando el comando: " + command);
		try {
			ChannelExec chan = (ChannelExec) session.openChannel("exec");
			chan.setCommand(command);
			chan.setOutputStream(System.out);
			
			InputStream in = chan.getErrStream();
			chan.connect();

			byte[] tmp = new byte[1024];
			while (true) {
				while (in.available() > 0) {
					int i = in.read(tmp, 0, 1024);
					if (i < 0)
						break;
					Display.rawLog(new String(tmp, 0, i));
				}
				if (chan.isClosed()) {
					Display.log("exit-status: " + chan.getExitStatus());
					break;
				}
				try {
					Thread.sleep(1000);
				} catch (Exception ee) {
				}
			}
			
			chan.disconnect();
		} catch (Exception e) {
			Display.log("Se ha producido un error inesperado: " + e.getMessage());
			e.printStackTrace();
		}
	}
}
